/**
 * 
 */
package leetCode;

/**
 * @author zhong
 *
 */
public class SurfaceAreaof3DShapes {
	public int surfaceArea(int[][] grid) {
		int N = grid.length;
		int res = 0;
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < N; j++) {
				if (grid[i][j] != 0) {
					res += 2;// 底面积
				}
				if (i != 0) {
					if (grid[i][j] < grid[i - 1][j]) {
						res += grid[i - 1][j] - grid[i][j];
					}
				} else {
					res += grid[i][j];
				}
				if (i != N - 1) {
					if (grid[i][j] < grid[i + 1][j]) {
						res += grid[i + 1][j] - grid[i][j];
					}
				} else {
					res += grid[i][j];
				}
				if (j != 0) {
					if (grid[i][j] < grid[i][j - 1]) {
						res += grid[i][j - 1] - grid[i][j];
					}
				} else {
					res += grid[i][j];
				}
				if (j != N - 1) {
					if (grid[i][j] < grid[i][j + 1]) {
						res += grid[i][j + 1] - grid[i][j];
					}
				} else {
					res += grid[i][j];
				}
			}
		}
		return res;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int[][] grid = { { 2, 2, 2 }, { 2, 1, 2 }, { 2, 2, 2 } };
		System.out.println(new SurfaceAreaof3DShapes().surfaceArea(grid));
	}

}
